<?php

namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class AdminAuth implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        $controllerArr = explode('\\', $request->controller);
        $controller = end($controllerArr);
        // 不需要中间件的控制器
        $exceptControllers = ['AuthController', 'CommonController'];
        if (in_array($controller, $exceptControllers)) {
            return $handler($request);
        }
        // 记住密码
        $cookie_admin = cookie('admin');
        if ($cookie_admin) {
            if (!session('admin')) {
                session(['admin' => json_decode($cookie_admin, true)]);
            }
        }
        $session_admin = session('admin');
        if (empty($session_admin)) {
            return redirect(url('/auth/login'));
        }

        return $handler($request);
    }
}
